const fs = require('fs');

// json文件的路径地址
const fileurl = 'files/student.json';

/**
 *封装student.json文件 增删改查的操作类
 */


exports.findAll = (callback) => {
  fs.readFile(fileurl, 'utf8', (error, data) => {
    if (error) {
      callback(`${fileurl}not found`);
    } else {
      callback(null, JSON.parse(data).students);
    }
  });
};

exports.findOne = (id, callback) => {
  fs.readFile(fileurl, 'utf8', (error, data) => {
    if (error) {
      callback(`${fileurl}not found`);
    } else {
      const studentsData = JSON.parse(data).students;
      const currentStudent = studentsData.find((value) => value.id === id);
      callback(null, currentStudent);
    }
  });
};

exports.update = (student, callback) => {
  fs.readFile(fileurl, 'utf8', (error, data) => {
    if (error) {
      callback(`${fileurl}not found`);
    } else {
      const studentsData = JSON.parse(data).students;
      // 判读这个人是否存在
      if (studentsData.find((vaue) => vaue.id === student.id)) {
        // 删除这个元素
        studentsData.splice(studentsData.findIndex((value) => value.id === student.id), 1);
        // 添加新的达到更新的效果
        studentsData.push(student);
        fs.writeFile(fileurl, JSON.stringify({ students: studentsData }), error, () => {
          if (error) {
            callback('file write faile');
          } else {
            callback(null, 'success');
          }
        });
      } else {
        callback('current user is null');
      }
    }
  });
};

exports.deleteStudent = (id, callback) => {
  if (id) {
    fs.readFile(fileurl, 'utf8', (error, data) => {
      if (error) {
        callback(`${fileurl}not found`);
      } else {
        const studentsData = JSON.parse(data).students;
        // 判读这个人是否存在
        if (studentsData.find((vaue) => vaue.id === id)) {
        // 删除这个元素
          studentsData.splice(studentsData.findIndex((value) => value.id === id), 1);

          fs.writeFile(fileurl, JSON.stringify({ students: studentsData }), error, () => {
            if (error) {
              callback('file write faile');
            } else {
              callback(null, 'success');
            }
          });
        } else {
          callback('current user is null');
        }
      }
    });
  } else {
    callback('id 不可为null 0 undefind');
  }
};


exports.insert = (student, callback) => {
  fs.readFile(fileurl, 'utf8', (error, data) => {
    if (error) {
      callback(`${fileurl}not found`);
    } else {
      const studentsData = JSON.parse(data).students;
      const stu = student;
      stu.id = studentsData.length + 1;
      studentsData.push(stu);
      fs.writeFile(fileurl, JSON.stringify({ students: studentsData }), error, () => {
        if (error) {
          callback('file write faile');
        } else {
          callback(null, 'success');
        }
      });
    }
  });
};
